package com.atguigu.gulimall.product;


import com.alibaba.fastjson.JSON;
import com.atguigu.search.GulimallSearchApplication;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.Map;


@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {GulimallSearchApplication.class})
public class GulimallSearchTestApplication {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Test
    public void textContext() {
        log.info("es高级客户端打印" + restHighLevelClient);
    }

    @Test
    public void indexDate() throws IOException {
        IndexRequest request = new IndexRequest("posts");
        request.id("1");
        String jsonString = "{" +
                "\"user\":\"kimchy\"," +
                "\"postDate\":\"2013-01-30\"," +
                "\"message\":\"trying out Elasticsearch\"" +
                "}";
        request.source(jsonString, XContentType.JSON);
        restHighLevelClient.index(request, RequestOptions.DEFAULT);
//        restHighLevelClient.indexAsync(request, RequestOptions.DEFAULT, new ActionListener<IndexResponse>() {
//            @Override
//            public void onResponse(IndexResponse indexResponse) {
//                return;
//            }
//
//            @Override
//            public void onFailure(Exception e) {
//                return;
//            }
//        });
    }


    @Test
    public void searchDate() throws IOException {
        //1.创建检索请求
        SearchRequest searchRequest = new SearchRequest();
        //指定索引
        searchRequest.indices("bank");
        //指定dsl
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //构造条件
        builder.query(QueryBuilders.matchQuery("address", "mill"));
        //按照年龄的条件聚合
        builder.aggregation(AggregationBuilders.terms("ageAgg").field("age").size(10))
                //计算平均薪资
                .aggregation(AggregationBuilders.avg("balanceAvg").field("balance"));
//        builder.query();
//        builder.from();
//        builder.size();
//        builder.aggregation()
        searchRequest.source(builder);
        //执行检索
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        SearchHit[] hitsHits = hits.getHits();
        for (SearchHit hitsHit : hitsHits) {
            //命中所有
            Map<String, Object> map = hitsHit.getSourceAsMap();
            String sourceAsString = hitsHit.getSourceAsString();
            Acount acount = JSON.parseObject(sourceAsString, Acount.class);
            System.out.println(acount);
        }
        //获取检索的分析信息
        Aggregations aggregations = searchResponse.getAggregations();
        Terms ageAgg = aggregations.get("ageAgg");
        for (Terms.Bucket bucket : ageAgg.getBuckets()) {
            Object key = bucket.getKey();
            long docCount = bucket.getDocCount();
            System.out.println(key);
            System.out.println(docCount);
        }
        Avg balanceAvg = aggregations.get("balanceAvg");
        System.out.println(balanceAvg.getValue());
        System.out.println(searchResponse.toString());
    }

    @Data
    @ToString
    static class Acount {
        private int account_number;

        private int balance;

        private String firstname;

        private String lastname;

        private int age;

        private String gender;

        private String address;

        private String employer;

        private String email;

        private String city;

        private String state;

        public void setAccount_number(int account_number) {
            this.account_number = account_number;
        }

        public int getAccount_number() {
            return this.account_number;
        }

        public void setBalance(int balance) {
            this.balance = balance;
        }

        public int getBalance() {
            return this.balance;
        }

        public void setFirstname(String firstname) {
            this.firstname = firstname;
        }

        public String getFirstname() {
            return this.firstname;
        }

        public void setLastname(String lastname) {
            this.lastname = lastname;
        }

        public String getLastname() {
            return this.lastname;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public int getAge() {
            return this.age;
        }

        public void setGender(String gender) {
            this.gender = gender;
        }

        public String getGender() {
            return this.gender;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public String getAddress() {
            return this.address;
        }

        public void setEmployer(String employer) {
            this.employer = employer;
        }

        public String getEmployer() {
            return this.employer;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getEmail() {
            return this.email;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getCity() {
            return this.city;
        }

        public void setState(String state) {
            this.state = state;
        }

        public String getState() {
            return this.state;
        }
    }
}

